package base.search.test;

import base.utils.PrintUtils;

import java.util.HashSet;
import java.util.Set;

public class SearchEmailDemo {

    public static void main(String[] args) {
        String strArray[] = {"test.email+alex@leetcode.com" , "test.e.mail+bob.cathy@leetcode.com" , "testemail+david@lee.tcode.com"};

        numUniqueEmails2(strArray);
    }


    public static int numUniqueEmails2(String[] emails) {
        Set<String> set = new HashSet<String>();
        for (String email : emails) {
            set.add(handleEmail(email));
            PrintUtils.print(email);
        }
        return set.size();
    }

    public static String handleEmail(String email) {
        StringBuilder sb = new StringBuilder();
        int n = email.length();
        // 是否遇到@符号
        boolean flag = false;
        for (int i=0; i<n; i++) {
            char c = email.charAt(i);
            if (!flag) {
                //没遇到@符号前，遇到.号一律 跳过
                if (c == '.') {
                    continue;
                }
                //遇到+号，往后跳一位，开始寻找@符号
                if (c == '+') {
                    i++;
                    while (i < n && email.charAt(i) != '@') {
                        i++;
                    }
                    c = email.charAt(i);
                    // 已经遇到@符号
                    flag = true;
                } else if(c == '@'){
                    // 没遇到+号，却遇到@符号了
                    flag = true;
                }
            }
            sb.append(c);
        }
        return sb.toString();
    }

}
